<template>
  <textarea
    :class="schema.commonFormControlClass"
    :name="field.name"
    :placeholder="field.placeholder"
    :rows="field.textareaRows"
    :value="formatValue(value)"
    :disabled="disabled"
    @input="onChange"></textarea>
</template>

<script>
  import _ from 'lodash'
  import InputPatterns from '../input-patterns'

  export default {
    props: {
      schema: {
        type: Object,
        default () {
          return {}
        }
      },
      value: {},
      name: String,
      field: Object,
      disabled: Boolean
    },
    computed: {
      inputPattern () {
        if (this.field.inputPattern) {
          return InputPatterns[this.field.inputPattern] || new RegExp(this.field.inputPattern)
        }
        return null
      }
    },
    methods: {
      onChange (e) {
        if (e.target.value === '') {
          this.$emit('input', null)
          return
        }
        if (!this.inputPattern || this.inputPattern.test(e.target.value)) {
          let v = e.target.value
          this._lastValue = v
          this.$emit('input', v)
        } else {
          this.$el.value = this.formatValue(this._lastValue)
        }
      },
      formatValue (v) {
        if (_.isNil(v) || _.isNaN(v)) {
          return ''
        }
        return v
      }
    }
  }
</script>
